//获取应用实例
//index.js
var that,
  api = new (require('../../utils/api.js')),
  headimg = api.getimgurl(),
  staticimg = api.getstaticimgurl(),
  QQMapWX = require('../../utils/qqmap-wx-jssdk.js'),
  qqmapsdk,
  util = new (require('../../utils/util.js'));
const app = getApp()


Page({
  data: {
    opencity: !1,
    pagesize: 15,
    start: 1,
    keeperlist: [],
    district: '',
    phoneNumber: '400-600-1909',
    headimg,
    keeperswitchindex: 0,
    lastlocationts: 0,
    switchindex: 0,
   // list: [{recycletype:{name:'废纸'},apply:{date:'2025.09.29 11:25',name:'李先生',ordernum:123,address:'吉安市英华嘉园',addressmore:'门卫'}}],
    list: [],


    fwzx: [
      {
        name: '客服电话',
        'path': '../pic/phone_icon.png'
        , tap: 'call'
      },
      {
        name: '同城服务',
        'path': staticimg + 'LOCATION1.png',
        tap: 'toaround'

      },
      {
        name: '分类知识',
        'path': staticimg + 'knowledge.png'
        , tap: 'classification'
      }
    ],
    weightarr: ['10-25公斤', '25-50公斤', '50-250公斤', '250公斤以上'],
    switchindex1: 1,
    imgUrls: [

    ],
    // city:'盐城市',
  },
  close(e) {
    let { ordernum } = e.currentTarget.dataset;
    console.log(ordernum, 'ordernum');
    wx.showModal({
      title: '提示',
      content: "确定要删除吗",
      success: res => {
        if (res.confirm) {
          api.delorder(ordernum, res => {
            if (res.data.issuccess == 1) {
              util.nocancelmodal('删除成功', '提示', () => {
                //刷新
                let { switchindex } = this.data;
                if (switchindex == 0) {
                  that.setData({ start: 0, list: [] }, () => {
                    that.getrecyclelist()
                  })
                } else if (switchindex == 1) {
                  that.setData({ start: 1, list: [] }, () => {
                    that.getagentlist(that.data.switchindex1)
                  })

                }
              })
            } else {
              util.nocancelmodal(res.data.msg, '提示', () => {
                //刷新
                // let{switchindex} = this.data;
                // if(switchindex==0){
                //   that.setData({start:1,list:[]},()=>{
                //     that.getrecyclelist()
                //   })
                // }else if(switchindex==1){
                //   that.setData({start:1,list:[]},()=>{
                //     that.getagentlist(that.data.switchindex1)
                //   })

                // }
              })
            }
          })

        }
      }
    })

  },
  officialerr(e) {
    console.log(e, 'officialerr');

  },
  toaround() {
    wx.navigateToMiniProgram({
      appId: 'wx056e2fe8a2d944da',
    })
    // let arr = ['盐湖区','吉州区','东营区']
    // if(wx.getStorageSync('samecity')=='T'){
    //   let {usertype}=that.data
    //   wx.navigateTo({
    //     url: '../aroundmap/aroundmap?usertype='+usertype,
    //   })
    // }else if(arr.indexOf(that.data.district)>-1){


    // }else{
    //   wx.showModal({
    //     title: '提示',
    //     content:'该功能暂未开放',
    //     showCancel:!1
    //   })
    // }

  },
  classification() {
    wx.navigateTo({
      url: '../classification/classification',
    })
  },

  switch(e) {
    let { code } = e.currentTarget.dataset, { switchindex, switchindex1 } = that.data;
    if (code == switchindex) return;

    that.setData({ switchindex: code, reachbtm: !1, start: 0, list: [] }, () => {
      if (code == 1) {
        //更新代理页面
        that.getagentlist(switchindex1)

      } else {
        that.getrecyclelist()
      }
    })
  },
  switch1(e) {
    let { code } = e.currentTarget.dataset, { switchindex1 } = this.data;
    if (code == switchindex1) return;
    that.setData({ switchindex1: code, reachbtm: !1, list: [], start: 1 }, () => {
      that.getagentlist(code)
    })
  },

  toorder(e) {
    wx.getSetting({
      success: res => {
        if (typeof (res.authSetting['scope.userLocation']) != 'undefined' && !res.authSetting['scope.userLocation']) {
          wx.showModal({
            content: '纸老头服务需要获取地址位置权限，是否前往开启',
            confirmText: '前往开启',
            success: res => {
              if (res.confirm) {
                wx.openSetting({
                  success: res => {
                    if (res.authSetting['scope.userLocation']) {
                      // 授权成功，重新定位
                      wx.getLocation({
                        success: res => {
                          let { latitude, longitude } = res
                          api.setlatlng({ latitude, longitude }, res => {
                          })

                          qqmapsdk.reverseGeocoder({
                            location: `${latitude},${longitude}`,
                            success: res => {
                              let { district, city } = res.result.address_component;
                              if (city == '东莞市') district = '东莞市'
                              api.writelog({ lat: latitude, lng: longitude, district })
                              wx.setStorageSync('location', res.result.location)
                              wx.setStorageSync('district', district)
                              wx.setStorageSync('city', res.result.address_component.city)
                              api.updatedistrict(district, city, res1 => {
                                if (res.list) {
                                  console.log(res1.list, 'updatedistrictupdatedistrict');

                                }
                              })
                              that.setData({ city: res.result.address_component.city, district })
                              api.checkrecycleright({ city: res.result.address_component.city, district, id: e.currentTarget.dataset.tid }, res => {
                                if (res.data.issuccess == 1) {

                                  wx.navigateTo({
                                    // url: '../order/order?type='+e.currentTarget.dataset.type,
                                    url: '../order/order?tid=' + e.currentTarget.dataset.tid,
                                  })
                                } else {
                                  util.nocancelmodal(res.data.msg)
                                  // util.nocancelmodal('春节放假中，请年后下单,谢谢您对纸老头回收的支持！')

                                }
                              })


                            }
                          })
                        }
                      });
                      //   that.startgettinglocation()
                    } else {
                      // 没有允许定位权限
                      wx.showToast({
                        title: '您拒绝了定位权限，将无法使用此功能，请前往开启',
                        icon: 'none'
                      });
                    }
                  }
                });
              } else {
                wx.showToast({
                  title: '您拒绝了定位权限，将无法使用此功能，请前往开启',
                  icon: 'none'
                });
              }
            }
          })
        } else {
          api.writelog({ district: that.data.district })
          api.checkrecycleright({ district: that.data.district, city: that.data.city, id: e.currentTarget.dataset.tid }, res => {
            if (res.data.issuccess == 1) {
              wx.navigateTo({
                // url: '../order/order?type='+e.currentTarget.dataset.type,
                url: '../order/order?tid=' + e.currentTarget.dataset.tid,
              })
            } else {
              util.nocancelmodal(res.data.msg)
              // util.nocancelmodal('春节放假中，请年后下单，谢谢您对纸老头回收的支持！')
            }
          })
        }
      }
    })




    //

    // return;


  },
  call() {

    wx.getSetting({
      success: res => {
        if (typeof (res.authSetting['scope.userLocation']) != 'undefined' && !res.authSetting['scope.userLocation']) {
          wx.showModal({
            content: '纸老头服务需要获取地址位置权限，是否前往开启',
            confirmText: '前往开启',
            success: res => {
              if (res.confirm) {
                wx.openSetting({
                  success: res => {
                    if (res.authSetting['scope.userLocation']) {
                      // 授权成功，重新定位
                      wx.getLocation({
                        success: res => {
                          let { latitude, longitude } = res
                          api.setlatlng({ latitude, longitude }, res => {
                          })
                          let { phoneNumber } = that.data
                          wx.makePhoneCall({
                            phoneNumber
                            // phoneNumber: '400-600-1909',
                          })
                        }
                      });
                      //   that.startgettinglocation()
                    } else {
                      // 没有允许定位权限
                      wx.showToast({
                        title: '您拒绝了定位权限，将无法使用此功能，请前往开启',
                        icon: 'none'
                      });
                    }
                  }
                });
              } else {
                wx.showToast({
                  title: '您拒绝了定位权限，将无法使用此功能，请前往开启',
                  icon: 'none'
                });
              }
            }
          })
        } else {
          let { phoneNumber } = that.data
          wx.makePhoneCall({
            phoneNumber
            // phoneNumber: '400-600-1909',
          })
        }
      }
    })



  },
  toorderdetail(e) {
    let { ordernum } = e.currentTarget.dataset
    wx.navigateTo({
      url: '../finishorderdetail/finishorderdetail?ordernum=' + ordernum,
    })
  },

  tocity() {
    wx.navigateTo({
      url: '../city/city',
    })
  },
  onLoad: function (options) {
    wx.showShareMenu({
      menus: ['shareAppMessage', 'shareTimeline'],
      complete: (res) => {
        console.log('showShareMenu', res);

      },
    })
    that = this;
    let shareid = 0;
    console.log(options, 'optionsoptions')
    if (options.q) {
      shareid = decodeURIComponent(options.q).replace('https://chinawzhs.cn/share?id=', '');
    }
    if (options.shareid) {
      shareid = options.shareid
    }
    console.log(111);
    that.setData({ shareid }, () => {
      if (app.logininfo) {
        // if(app.logininfo.user.type=='STOREKEEPER'){
        //   wx.navigateTo({
        //     url: '../store/store',
        //   })
        // }else{
        //   that.getdata(app.logininfo)
        // }
        that.getdata(app.logininfo)

      } else {
        util.setwatcher(app, this.afterlogin)
      }
    })
    qqmapsdk = new QQMapWX({
      key: getApp().globalData.mapkey// 必填
    });

  },
  toprice() {



    wx.getSetting({



      success: res => {
        if (typeof (res.authSetting['scope.userLocation']) != 'undefined' && !res.authSetting['scope.userLocation']) {
          wx.showModal({
            content: '纸老头服务需要获取地址位置权限，是否前往开启',
            confirmText: '前往开启',
            success: res => {
              if (res.confirm) {
                wx.openSetting({
                  success: res => {
                    if (res.authSetting['scope.userLocation']) {
                      // 授权成功，重新定位
                      wx.getLocation({
                        success: res => {
                          let { latitude, longitude } = res
                          api.setlatlng({ latitude, longitude }, res => {
                          })

                          wx.navigateTo({
                            url: '../price/price',
                          })
                        }
                      });
                      //   that.startgettinglocation()
                    } else {
                      // 没有允许定位权限
                      wx.showToast({
                        title: '您拒绝了定位权限，将无法使用此功能，请前往开启',
                        icon: 'none'
                      });
                    }
                  }
                });
              } else {
                wx.showToast({
                  title: '您拒绝了定位权限，将无法使用此功能，请前往开启',
                  icon: 'none'
                });
              }
            }
          })
        } else {

          wx.navigateTo({
            url: '../price/price',
          })
        }
      }
    })


  },
  afterlogin: {
    logininfo: res => {
      console.log('app.logininfo', res);
      // if(res.user.type=='STOREKEEPER'){
      //   wx.navigateTo({
      //     url: '../store/store',
      //   })
      // }else{

      // }
      that.getdata(res);
    }
  },

  /**
   * 
   * @param {库管员} e 
   */
  keepswitch(e) {
    let { keeperswitchindex } = this.data, { code } = e.currentTarget.dataset;
    if (code == keeperswitchindex) return;

    that.setData({ keeperswitchindex: code, keeperlist: [] }, res => {
      that.getkeeperlist(code)
    })
  },

  getkeeperlist(type) {

    wx.showLoading({
      title: '加载中',
    })
    api.keeper_getlist(type, res => {
      wx.hideLoading()
      if (res.data.issuccess == 1) {
        let newlist = res.data.list, { keeperlist } = that.data;
        newlist.forEach((x, i) => {
          newlist[i]['date'] = util.formatTimenosecend(new Date(newlist[i]['date'] * 1000))
        })
        keeperlist = keeperlist.length > 0 ? keeperlist.concat(newlist) : newlist
        that.setData({ keeperlist })
      } else {
        util.nocancelmodal(res.data.msg)
      }
    })

  },



  tonav(e) {
    let plugin = requirePlugin('routePlan');
    let key = 'SZQBZ-DHWC4-FW5UG-KSTIT-YGEC6-JZFV4';  //使用在腾讯位置服务申请的key
    let referer = '回收小程序';   //调用插件的app的名称
    let endPoint = JSON.stringify({  //终点

      'name': e.currentTarget.dataset.address,
      'latitude': parseFloat(e.currentTarget.dataset.lat),
      'longitude': parseFloat(e.currentTarget.dataset.lng)
    });
    wx.navigateTo({
      url: 'plugin://routePlan/index?key=' + key + '&referer=' + referer + '&endPoint=' + endPoint + '&navigation=1'
    });
  },
  getdata(info) {
    // console.log(info,'info');
    let { imgUrls, shareid } = that.data;
    console.log(shareid, 'shareidshareid');
    if (Number(shareid) > 0) {
      api.checkshare(shareid, res => {
        console.log('checkshare');
      })

    }
    that.setData({ usertype: info.user.type })
    if(info.user.isblock=='1'){
      wx.reLaunch({
        url: '../block/block',
      })
      // return;
    }
 
    wx.getLocation({
      success: res => {
        qqmapsdk.reverseGeocoder({
          location: `${res.latitude},${res.longitude}`,
          success: res => {
            let { city, district } = res.result.address_component
            if (city == '东莞市') district = '东莞市'
            api.writelog({ lat: res.latitude, lng: res.longitude, district })

            wx.setStorageSync('location', res.result.location)
            wx.setStorageSync('district', district)
            wx.setStorageSync('city', res.result.address_component.city)
            if (info.user.type == 'CONSUMER') {
              api.updatedistrict(district, city, res1 => {
                if (res1.data.list) {
                  console.log(res1.list, 'updatedistrictupdatedistrict');
                  let list = res1.data.list
                  list.forEach(x => {
                    x['path'] = headimg + x.topimg
                  })
                  app.yjxd = res1.data.list;
                  that.setData({ yjxd: res1.data.list })

                }
              })
            }
            that.setData({ city: res.result.address_component.city, district })
            console.log('qqmapsdkres', res.result.address_component.city);
          },
          complete:res=>{
            console.log(res,'complete');
          }
        })

      },
      complete:res=>{
        console.log('getloca--complete',res);
      }
    })

    if (info.user.type == 'CONSUMER') {
      console.log(this.data.district, 'district')
      api.getswipers(res => {
        wx.hideLoading({
          complete: (res) => { },
        })
        if (res.data.issuccess == 1) {
          imgUrls = res.data.list
          that.setData({ imgUrls })
          console.log(res, 'ress')
        }
      })
    } else if (info.user.type == 'RECYCLER' || info.user.type == 'AGENT' || info.user.type == 'OARECYCLER' || info.user.type == 'OAAGENT') {
      if (info.user.type == 'AGENT') {
        wx.setTabBarItem({
          index: 0,
          text: '订单管理'
        })
      }

      wx.getSetting({
        success: res => {
          if (typeof (res.authSetting['scope.userLocation']) != 'undefined' && !res.authSetting['scope.userLocation']) {
            wx.openSetting({
              success: res => {
                if (res.authSetting['scope.userLocation']) {
                  // 授权成功，重新定位
                  wx.getLocation({
                    success: res => {

                    }
                  });
                  that.startgettinglocation()
                } else {
                  // 没有允许定位权限
                  wx.showToast({
                    title: '您拒绝了定位权限，将无法使用XX功能',
                    icon: 'none'
                  });
                }
              }
            });
          } else {
            that.startgettinglocation()
          }
        }
      })




      that.setData({ start: 0, list: [] }, () => {
        that.getrecyclelist()
      })
      // that.getrecyclelist()
    } else if (info.user.type == 'STOREKEEPER') {
      that.getkeeperlist(that.data.keeperswitchindex)
      return;
    }
    api.Recycletypegetlist(res => {
      if (res.data.issuccess == 1) {
        let list = res.data.list
        list.forEach(x => {
          x['path'] = headimg + x.topimg
        })
        app.yjxd = res.data.list;
        that.setData({ yjxd: res.data.list })
      }
    })
    api.getservicephone(res => {
      if (res.data.issuccess == 1) {
        that.setData({ phoneNumber: res.data.phone || "4006001909" })
      }
    })
  },

  tostore(e) {
    let { id, name } = e.currentTarget.dataset;
    wx.navigateTo({
      url: '../store/store?id=' + id + "&name=" + name,
    })
  },

  startgettinglocation() {
    wx.startLocationUpdateBackground({
      complete: (res) => { console.log(res, 'startLocationUpdateBackground') },
    })
    wx.onLocationChange((result) => {
      console.log(11111);
      let { lastlocationts } = this.data, ts = new Date().getTime();
      if (ts - lastlocationts > 1000 * 15) { //15秒更新一次
        console.log(result, 'resultresultresult');

        let { latitude, longitude } = result
        api.setlatlng({ latitude, longitude }, res => {
        })
        that.setData({ lastlocationts: ts })
      }


    })
  },

  getrecyclelist() {
    let { pagesize, start,list } = that.data;
    wx.showLoading({
      title: '加载中',
    })
    console.log('getorderinglist');

    api.getorderinglist( res => {
      wx.hideLoading({
        complete: (res) => { },
      })
      wx.stopPullDownRefresh()
      if (res.data.issuccess == 1) {
        //let { list } = res.data;

        res.data.list.forEach((x, i) => {
          x['date'] = util.toDate1(x.orderdate)//util.formatTimenosecend(new Date(x.orderdate))
          x['weight'] = that.data.weightarr[x.apply.weightsection - 1]
          x['state'] = x.apply.state// list[i]['apply']['state']
          x['ordernum'] = x.apply.ordernum //list[i]['apply']['ordernum']
          list.push(x)
          that.formSub(x.apply.lat + "," + x.apply.lng)
          //  list[i]['state'] =
        })
        that.setData({ list, })
      }
    })
  },

  getagentlist(type) {
    let { pagesize, start } = that.data;
    wx.showLoading({
      title: '加载中',
    })
    api.getmymemberlist({ type, pagesize, start }, res => {
      wx.hideLoading({
        complete: (res) => { },
      })
      wx.stopPullDownRefresh()
      if (res.data.issuccess == 1) {
        let { list } = res.data, oldlist = that.data.list;

        list.forEach((x, i) => {
          list[i]['date'] = util.formatTimenosecend(new Date(x.odate * 1000))
          list[i]['weight'] = that.data.weightarr[x.weightsection - 1]
          that.formSub(x.lat + "," + x.lng)
          //  list[i]['state'] =
        })
        if (oldlist.length > 0) {
          list = oldlist.concat(list);
        }
        console.log(list.length, 'list.length');
        that.setData({ list, start: start + pagesize, total: res.data.total, reachbtm: list.length == Number(res.data.total) })
      }
    })
  },

  toorderdetail(e) {
    let { ordernum } = e.currentTarget.dataset
    wx.navigateTo({
      url: '../finishorderdetail/finishorderdetail?ordernum=' + ordernum,
    })
  },

  tomyorder() {
    wx.navigateTo({
      url: '../myorder/myorder',
    })
  },

  formSub(end) {
    var _this = this;
    //调用距离计算接口
    qqmapsdk.calculateDistance({
      mode: 'straight',//可选值：'driving'（驾车）、'walking'（步行），不填默认：'walking',可不填
      //from参数不填默认当前地址
      //获取表单提交的经纬度并设置from和to参数（示例为string格式）
      from: '', //若起点有数据则采用起点坐标，若为空默认当前地址
      to: end, //终点坐标
      success: function (res) {
        //成功后的回调
        //  console.log(res);
        var res = res.result;
        var dis = that.data.distance || [];
        for (var i = 0; i < res.elements.length; i++) {
          dis.push(res.elements[i].distance); //将返回数据存入dis数组，
        }
        // console.log(dis);
        _this.setData({ //设置并更新distance数据
          distance: dis
        });
      },
      fail: function (error) {
        console.error(error);
      },
      complete: function (res) {
        console.log(res);
      }
    });
  },
  cancel(e) {
    wx.showModal({
      title: '提示',
      content: '确定要拒单吗?',
      success: res => {
        if (res.confirm) {
          api.recyclercancel(e.currentTarget.dataset.ordernum, res => {
            if (res.data.issuccess == 1) {
              util.nocancelmodal('拒绝成功！', "", res => {
                that.setData({ start: 0, list: [] }, () => {
                  that.getrecyclelist()
                })
                // that.getrecyclelist()
              })
            }
          })
        }
      }
    })
  },

  onPullDownRefresh() {
    if (that.data.usertype == 'RECYCLER' || that.data.usertype == 'AGENT' || that.data.usertype == 'OARECYCLER' || that.data.usertype == 'OAAGENT') {
      wx.showLoading({
        title: '加载中',
      })
      let { switchindex, switchindex1 } = this.data;
      if (switchindex == 0) {
        that.setData({ start: 0,list:[] }, () => {
          that.getrecyclelist()
        })
      } else if (switchindex == 1) {
        that.setData({ start: 0, list: [] }, () => {
          that.getagentlist(switchindex1)
        })

      }


    } else {
      wx.stopPullDownRefresh({
        complete: (res) => { },
      })
    }

  },

  onReachBottom() {
    let { switchindex, switchindex1, usertype, reachbtm,start , pagesize,list,total } = this.data;
    if (usertype == 'RECYCLER' || usertype == 'AGENT' || usertype == 'OARECYCLER' || usertype == 'OAAGENT') {

      if (switchindex == 1) {
        if (reachbtm) {
          wx.showToast({
            title: '已经到底了',
            icon: 'none'
          })
          return;
        } else {

          that.getagentlist(switchindex1)

        }
      }else if(switchindex == 0){
        console.log(list.length,'listlist');
        console.log(total,'totaltotal');
        if (list.length<total) {
          that.setData({ start: start + pagesize }, () => {
            that.getrecyclelist()

          })
        
        } else {
          wx.showToast({
            title: '已经到底了',
            icon: 'none'
          })
          return;
        }
      }




    }




    // let{switchindex,switchindex1,usertype,reachbtm} = this.data;
    // if(switchindex==1&&usertype=='AGENT'){
    //   console.log('onReachBottom');
    //   if(reachbtm){
    //     wx.showToast({
    //       title: '已经到底了',
    //       icon:'none'
    //     })
    //     return;
    //   }else{
    //     wx.showLoading({
    //       title: '加载中',
    //     })
    //     that.getagentlist(switchindex1)
    //   }


    // }



  },



  accept(e) {
    wx.showModal({
      title: '提示',
      content: '确定要接单吗?',
      success: res => {
        if (res.confirm) {
          api.recycleraccept(e.currentTarget.dataset.ordernum, res => {
            if (res.data.issuccess == 1) {
              util.nocancelmodal('接单成功！', "", res => {
                that.setData({ start: 0, list: [] }, () => {
                  that.getrecyclelist()
                })
                // that.getrecyclelist()
              })
            }
          })
        }
      }
    })
  },

  onShow: function () {
    let city = wx.getStorageSync("city")
    if (city) {
      that.setData({ city: city.name })
    }
    if (that.data.keepneedfresh) {
      that.setData({ keeperlist: [], keepneedfresh: !1 }, () => {
        that.getkeeperlist(that.data.keeperswitchindex)
        return;
      })
    }
  },


})
